package com.naiterui.ehp.bs.wechat.service.impl;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.naiterui.common.redis.RedisUtil;
import com.naiterui.ehp.bs.wechat.config.WeChatConfig;
import com.naiterui.ehp.bs.wechat.constants.WeChatCache;
import com.naiterui.ehp.bs.wechat.properties.WeChatProperties;
import com.naiterui.ehp.bs.wechat.service.IAccessTokenService;
import com.naiterui.ehp.bs.wechat.utils.WeChatApiUtil;

/**
 * @author zhoupeipei
 * @date 2019-06-14 15:28
 * @since 1.0.0
 */
@Service
public class AccessTokenServiceImpl implements IAccessTokenService {
    @Autowired
    WeChatConfig weChatConfig;
    @Autowired
    IAccessTokenService accessTokenService;

    @Override
    public String accessToken() {
        WeChatProperties configProperties = weChatConfig.paProperties();
        String appId = configProperties.getAppId();
        String accessToken = Optional.ofNullable(appId)
                                     .map(s -> WeChatCache.accessTokenKey(appId))
                                     .map(cacheKey -> RedisUtil.valueOps().getString(cacheKey))
                                     .orElse(null);
        if (null == accessToken) {
            accessToken = WeChatApiUtil.refreshAccessToken(appId, configProperties.getAppSecret());
        }

        return accessToken;
    }
}
